import React from 'react'
import './css/index.css'
import { SearchOutlined, RollbackOutlined, LoadingOutlined, PlusOutlined, DeleteTwoTone } from '@ant-design/icons'
import { useEffect, useState, useRef, useMemo } from 'react';
import axios from 'axios'
import moment from 'moment';
import { Button, Modal, message, Upload } from 'antd';
// import { format } from 'date-fns';
export default function index() {
  const [data, setdata] = useState([])
  const [id, setId] = useState('');
  const [cate, setCate] = useState('')
  const [time, setTime] = useState('')
  const [da, setDa] = useState([])
  const [xiao, setXiao] = useState([])
  const [title, setTitle] = useState('')
  const show = () => {
    axios.get(`http://localhost:3000/ljy/ljyshow`).then(res => {
      setdata(res.data.data)
      console.log('走过了展示所有数据');
    })
  }
  //视口高度
  const [height, setheight] = useState(100)
  //单个元素高度
  const [onHeight, setonHeight] = useState(25)
  //最大容积
  const [maxHeight, setmaxHeight] = useState(0)
  //滚动事件
  const scrollshu = useRef(null)
  const [start, setStart] = useState(0);
  //滚动的结束位置
  const [end, setEnd] = useState(0);
  useEffect(() => {
    setmaxHeight(~~(height / onHeight))
    setStart()
    show()
  }, [])
  useEffect(() => {
    show()
  }, [id])
  //上空白
  const shang = useMemo(() => {
    return start * onHeight
  },)
  //下空白
  const xia = useMemo(() => {
    return (data.length - end) * onHeight
  })
  const handleScroll = () => {
    console.log('滚动距离顶的', scrollshu.current.scrollTop);
    setStart(~~(scrollshu.current.scrollTop / onHeight));
  }
  const endIndex = useMemo(() => {
    //开始位置+最大容积数量
    let endindex = start + maxHeight;
    //如果最后一个元素不存在
    // if (!data[endindex]) {
    //   endindex = data.length - 1
    // }
    return endindex
  })
  const showList = useMemo(() => {
    console.log('showList', data);
    return data.slice(start, endIndex)
  })

  const submit = () => {
    console.log(cate, time, title, da, xiao);
    axios.post('http://localhost:3000/ljy/select', {
      cate: cate,
      time: time,
      title: title,
      da: da,
      xiao: xiao
    }).then(res => {
      console.log('输出的数据', res.data.data);
      setdata(res.data.data)
      console.log('过滤后的数据', data);
    })
  }
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };
  const handleOk = () => {
    setIsModalOpen(false);
    const from = {
      title: addtitle,
      price: addprice,
      state: addstate,
      time: addtime,
      cate: addcate,
      uid: adduid,
      name: addname,
      img: imageUrl
    }
    console.log('添加之后的数据', from);
    axios.post('http://localhost:3000/ljy/add', from)
    show()
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //图片上传
  const [loading, setLoading] = useState(false);
  //添加的数据
  //商品名称
  const [addtitle, setAddtitle] = useState('');
  //商品价格
  const [addprice, setAddprice] = useState('');
  //商品状态
  const [addstate, setAddstate] = useState(false);
  //商品编号
  const [adduid, setAdduid] = useState('');
  //商品分类
  const [addcate, setAddcate] = useState('');
  //更改人
  const [addname, setAddname] = useState('');
  //更改时间
  const [addtime, setAddtime] = useState('');
  //上传的图片
  const [imageUrl, setImageUrl] = useState();

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    // 获取文件列表中的第一个文件的响应数据
    const response = info.fileList[0].response;
    if (response && response.path) {
      const filePath = response.path;
      const normalizedPath = filePath.replace(/\\/g, '/');
      console.log('上传成功，文件路径:', normalizedPath);
      // 将路径设置到状态或变量中
      setImageUrl(normalizedPath);
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  const [isCopied, setIsCopied] = useState(false);
  const copy = (item) => {
    console.log(item);
    navigator.clipboard.writeText(item.uid.item.name);
  }
  //修改
  const [upisModalOpen, setUpisModalOpen] = useState(false);
  //商品名称
  const [uptitle, setUptitle] = useState('');
  //商品价格
  const [upprice, setUpprice] = useState('');
  //商品状态
  const [upstate, setUpstate] = useState(false);
  //商品编号
  const [upuid, setUpuid] = useState('');
  //商品分类
  const [upcate, setUpcate] = useState('');
  //更改人
  const [upname, setUpname] = useState('');
  //更改时间
  const [uptime, setUptime] = useState('');
  //上传的图片
  const [image, setImage] = useState('');

  const upshowModal = (item) => {
    setId(item._id);
    setUpuid(item.uid);
    setUptitle(item.title);
    setUpprice(item.price);
    setUpcate(item.cate);
    console.log(item.cate);
    setUpname(item.name);
    setUptime(item.time);
    setImage(item.img);
    //  console.log('即将要回显的数据',xian);
    setUpisModalOpen(true);
  };
  const uphandleOk = () => {
    const data = {
      id: id,
      uid: upuid,
      title: uptitle,
      price: upprice,
      state: upstate,
      cate: upcate,
      name: upname,
    }
    axios.post('http://localhost:3000/ljy/update', data)
    setUpisModalOpen(false);
    show()
  };
  const uphandleCancel = () => {
    setUpisModalOpen(false);
  };
  const jia = (id) => {
    axios.post('http://localhost:3000/ljy/jia', { id: id })
    show()

  }
  const del = (id) => {
    axios.post('http://localhost:3000/ljy/del', { id: id })
    show()
  }
  return (
    <div>
      <div className='ljybox'>
        <div className='box1'>商品管理</div>
        <div className='ljybox2'>
          <div className='wo'>
            <span style={{ marginRight: '15px' }}>分类</span>
            <select name="" id="" onChange={(e) => setCate(e.target.value)}>
              <option value="">请选择</option>
              <option value="67b819086ddfef81d91bcaca">生活照料</option>
              <option value="67b819086ddfef81d91bcac5">临床护理</option>
              <option value="67b819086ddfef81d91bcac6">康复护理</option>
              <option value="67b819086ddfef81d91bcac7">心里关怀</option>
              <option value="67b819086ddfef81d91bcac8">上门做饭</option>
              <option value="67b819086ddfef81d91bcac9">健康管理</option>
              <option value="67b819086ddfef81d91bcacb">陪同就医</option>
              <option value="67b819086ddfef81d91bcac4">日常清洁</option>
            </select>
          </div>
          <div className='wo1'>
            <span style={{ marginRight: '15px' }}>选择日期</span>
            <input type="date" onChange={(e) => setTime(e.target.value)} />
          </div>
          <div className='aa'>
            <span style={{ marginRight: '15px' }}>价格</span>
            <input type="text" placeholder='最低价格' onChange={(e) => setXiao(e.target.value)} />
            - <input type="text" placeholder='最高价格' onChange={(e) => setDa(e.target.value)} />
          </div>
        </div>
        <div className='select'>
          <input type="text" placeholder='请输入关键字' onChange={(e) => setTitle(e.target.value)} />
          <span><button style={{
            width: '1rem', height: "1rem",
            borderRadius: '0.2rem', backgroundColor: '#3DD4A7', border: 'none', marginLeft: "0.5rem"
          }}><SearchOutlined onClick={() => submit()} /></button></span>
          <span><button style={{
            width: '1rem', height: "1rem",
            borderRadius: '0.2rem', marginLeft: "0.5rem", border: 'none'
          }}><RollbackOutlined /></button></span>
        </div>
      </div>
      <div>
        <div className='di'>
          <div style={{ marginLeft: '24rem', }}>
            <span>
              <button style={{
                width: '2rem', height: "1rem", borderRadius: "0.2rem", border: 'none',
                backgroundColor: '#3DD4A7', color: 'white'
              }} onClick={showModal}>
                新增</button></span>
            <div>
              <Modal title="新增订单" open={isModalOpen} onOk={uphandleOk} onCancel={uphandleCancel} footer={false}>
                <div className='tan'>
                  <div className='top'>
                    <div>商品名称：<input type="text" placeholder='请输入名称' onChange={(e) => setAddtitle(e.target.value)} /></div>
                    <div>商品编码 :<input type="text" placeholder='请输入编码' onChange={(e) => setAdduid(e.target.value)} /></div>
                    <div>分类:<select name="" id="" onChange={(e) => setAddcate(e.target.value)}>
                      <option value="67b819086ddfef81d91bcaca">生活照料</option>
                      <option value="67b819086ddfef81d91bcac5">临床护理</option>
                      <option value="67b819086ddfef81d91bcac6">康复护理</option>
                      <option value="67b819086ddfef81d91bcac7">心里关怀</option>
                      <option value="67b819086ddfef81d91bcac8">上门做饭</option>
                      <option value="67b819086ddfef81d91bcac9">健康管理</option>
                      <option value="67b819086ddfef81d91bcacb">陪同就医</option>
                      <option value="67b819086ddfef81d91bcac4">日常清洁</option>
                    </select></div>
                  </div>
                  <div>
                    图片:<Upload
                      name="avatar"
                      listType="picture-card"
                      className="avatar-uploader"
                      showUploadList={false}
                      action="http://localhost:3000/ljy/upload"
                      // beforeUpload={beforeUpload}
                      onChange={handleChange}
                    >
                      {imageUrl ? (
                        <img
                          src={imageUrl}
                          alt="avatar"
                          style={{
                            width: '100%',
                          }}
                        />
                      ) : (
                        uploadButton
                      )}
                    </Upload>
                  </div>
                  <div className='button'>
                    <div>价格：<input type="text" placeholder='请输入价格' onChange={(e) => setAddprice(e.target.value)} /></div>
                    <div>更新人： <input type="text" placeholder='请输入更新人' onChange={(e) => setAddname(e.target.value)} /></div>
                    <div>更新时间 :<input type="date" onChange={(e) => setAddtime(e.target.value)} /></div>
                  </div>
                  <div className='an'>
                    <button style={{
                      width: "2rem", backgroundColor: "#3DD4A7", border: "none"
                      , height: "1rem", borderRadius: '0.2rem'
                    }} onClick={handleOk}>提交审核</button>
                    <button style={{
                      backgroundColor: "white", border: "1px solid grey", marginLeft: "0.5rem"
                      , height: '1rem', width: '1.5rem', borderRadius: '0.2rem'
                    }} onClick={handleOk}>返回</button>
                  </div>
                </div>
              </Modal>
            </div>
            <div className='scroll' onScroll={handleScroll} ref={scrollshu}>
              <div style={{ paddingTop: shang + 'px', paddingBottom: xia + 'px' }}>
                <table className='table' >
                  <tr style={{ fontSize: '0.5rem' }}>
                    <td>商品信息</td>
                    <td>编码</td>
                    <td>分类</td>
                    <td>价格</td>
                    <td>状态</td>
                    <td>更新人</td>
                    <td>更新时间</td>
                    <td>操作</td>
                  </tr>
                  {
                    showList.map((item) => {
                      return <tr className='div1'>
                        <td><img src={item.img} alt="" /><span style={{ position: 'relative', bottom: '1rem', left: '0.5rem' }}>{item.title}</span></td>
                        <td>{item.uid}</td>
                        <td>{item.cate?.title}</td>
                        <td>{item.price}</td>
                        <td >{item.state ? "上架" : '下架'}</td>
                        <td>{item.name}</td>
                        <td>{moment(item.time).format('YYYY-MM-DD')}</td>
                        <td>
                          <div>
                            <button style={{
                              marginRight: "0.4rem", color: '#3DD4A7',
                              border: 'none', backgroundColor: 'white'
                            }} onClick={() => copy(item)}>复制</button>
                            <button style={{
                              color: '#3DD4A7', border:
                                'none', backgroundColor: 'white'
                            }} onClick={() => upshowModal(item)}>编辑</button>
                            <div>
                              <Modal title="新增订单" open={upisModalOpen} onOk={handleOk} onCancel={handleCancel} footer={false}>
                                <div className='tan'>
                                  <div className='top'>
                                    <div>商品名称：<input type="text" placeholder='请输入名称' onChange={(e) => setUptitle(e.target.value)} value={uptitle} /></div>
                                    <div>商品编码 :<input type="text" placeholder='请输入编码' onChange={(e) => setUpuid(e.target.value)} value={upuid} /></div>
                                    <div>分类:<select name="" id="" onChange={(e) => setUpcate(e.target.value)} value={upcate}>
                                      <option value="请选择">请选择</option>
                                      <option value="67b819086ddfef81d91bcaca">生活照料</option>
                                      <option value="67b819086ddfef81d91bcac5">临床护理</option>
                                      <option value="67b819086ddfef81d91bcac6">康复护理</option>
                                      <option value="67b819086ddfef81d91bcac7">心里关怀</option>
                                      <option value="67b819086ddfef81d91bcac8">上门做饭</option>
                                      <option value="67b819086ddfef81d91bcac9">健康管理</option>
                                      <option value="67b819086ddfef81d91bcacb">陪同就医</option>
                                      <option value="67b819086ddfef81d91bcac4">日常清洁</option>
                                    </select></div>
                                  </div>
                                  <div className='button'>
                                    <div>价格：<input type="text" placeholder='请输入价格' onChange={(e) => setUpprice(e.target.value)} value={upprice} /></div>
                                    <div>更新人： <input type="text" placeholder='请输入更新人' onChange={(e) => setUpname(e.target.value)} value={upname} /></div>
                                  </div>
                                  <div className='an'>
                                    <button style={{
                                      width: "2rem", backgroundColor: "#3DD4A7", border: "none"
                                      , height: "1rem", borderRadius: '0.2rem'
                                    }} onClick={uphandleOk}>提交审核</button>
                                    <button style={{
                                      backgroundColor: "white", border: "1px solid grey", marginLeft: "0.5rem"
                                      , height: '1rem', width: '1.5rem', borderRadius: '0.2rem'
                                    }} onClick={uphandleOk}>返回</button>
                                  </div>
                                </div>
                              </Modal>
                            </div>
                          </div>
                          <div>
                            <button style={{
                              marginRight: "0.4rem", color: 'red',
                              border: 'none', backgroundColor: 'white'
                            }} onClick={() => del(item._id)}>删除</button>
                            <button style={{
                              color: '#3DD4A7', border:
                                'none', backgroundColor: 'white'
                            }}
                              onClick={() => jia(item._id)}>{item.state ? "下架" : '上架'}</button>
                          </div>
                        </td>
                      </tr>
                    })
                  }
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
